﻿using System;
using System.Windows.Forms;
using SdmxMl.Manager;
using SdmxMl.GenericData;
using SdmxMl.Common;

namespace SdmxMl.Helper
{
    /// <summary>
    /// Construct tree base for Artefacts manager containers
    /// </summary>
    public class TreeSm
    {

        public static void FillTree(TreeView tv, SmManager sm)
        {
            tv.BeginUpdate();
            tv.Nodes.Clear();
            TreeNode ndMgr = null;

            DataSetManager dsm = null;
            MetadataSetManager msm = null;

            foreach (SdmxArtefactType atype in Enum.GetValues(typeof(SdmxArtefactType)))
            {
                ArtefactManager a = sm.GetArtefactManager(atype);

                if (a != null && a.Count > 0)
                {
                    dsm = a as DataSetManager;
                    msm = a as MetadataSetManager;

                    int iconIndex = GetArtefactIconIndex(a);
                    ndMgr = new TreeNode(a.ToString(), iconIndex, iconIndex);
                    ndMgr.Tag = a;
                    tv.Nodes.Add(ndMgr);
                    FillArtefactTree(a, ndMgr);
                }
            }
            
            tv.EndUpdate();
        }

        static int GetArtefactIconIndex(ArtefactManager a)
        {
            int iconIndex = 1;
            if (a is DataSetManager)
                iconIndex = 3;
            else if (a is MetadataSetManager)
                iconIndex = 2;
            return iconIndex;
        }

        static void FillArtefactTree(ArtefactManager am, TreeNode parentNode)
        {
            DataSetManager dsm = am as DataSetManager;
             if (dsm != null)
            {
                foreach (DataSetType d in dsm.DataSetList)
                    d.FillNode(parentNode);
            }
            else
            {
                foreach (Artefact a in am.ArtefactList)
                    a.FillNode(parentNode);
            }
        }
    }
}
